package cn.leonis.leetcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Tobi
 * @date 2021-06-09 0:55
 * 存在重复值
 */
public class ContainDuplicatesSolution {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        ContainDuplicatesSolution solution = new ContainDuplicatesSolution();
        System.out.println(solution.containsDuplicate1(nums));
    }

    /**
     * 解法一：通过一个hashset临时保存
     * @param nums
     * @return
     */
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> integers = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (integers.contains(nums[i])) {
                return true;
            }
            integers.add(nums[i]);
        }
        return false;
    }

    /**
     * 解法二：通过一个hashset临时保存
     * @param nums
     * @return
     */
    public boolean containsDuplicate1(int[] nums) {
        Set<Integer> integers = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (!integers.add(nums[i])) {
                return true;
            }
        }
        return false;
    }

    /**
     * 执行比较好的解法
     * @param nums
     * @return
     */
    public boolean containsDuplicate2(int[] nums) {
        Arrays.sort(nums);
        for (int i = 1; i < nums.length; i++)
            if (nums[i] == nums[i-1])
                return true;
        return false;
    }
}
